package com.ruoyi.pay.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.pay.domain.PayCoinUser;
import com.ruoyi.pay.domain.PayOrder;
import com.ruoyi.pay.domain.vo.PayOrderVO;
import com.ruoyi.pay.mapper.PayCoinUserMapper;
import com.ruoyi.pay.mapper.PayOrderMapper;
import com.ruoyi.pay.service.IPayOrderService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wx.domain.WxMaForm;
import com.ruoyi.wx.domain.WxPayOrderNotifyInfo;
import com.ruoyi.wx.domain.WxPayReturnInfo;
import com.ruoyi.wx.service.WxMaPayService;

import cn.hutool.core.date.DateUtil;

/**
 * 支付订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-08-04
 */
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {
   
	@Autowired
    private PayOrderMapper payOrderMapper;
	
	@Autowired
	private PayCoinUserMapper payCoinUserMapper;
	
	@Autowired
    private WxMaPayService wxMaPayService;
	
	@Autowired
	private ISysUserService sysUserService;

    /**
     * 查询支付订单
     * 
     * @param id 支付订单主键
     * @return 支付订单
     */
    @Override
    public PayOrder selectPayOrderById(String id)
    {
        return payOrderMapper.selectPayOrderById(id);
    }

    /**
     * 查询支付订单列表
     * 
     * @param payOrder 支付订单
     * @return 支付订单
     */
    @Override
    public List<PayOrder> selectPayOrderList(PayOrder payOrder)
    {
        return payOrderMapper.selectPayOrderList(payOrder);
    }

    /**
     * 修改支付订单
     * 
     * @param payOrder 支付订单
     * @return 结果
     */
    @Override
    public int updatePayOrder(PayOrder payOrder)
    {
        payOrder.setUpdateTime(DateUtils.getNowDate());
        return payOrderMapper.updatePayOrder(payOrder);
    }

    /**
     * 批量删除支付订单
     * 
     * @param ids 需要删除的支付订单主键
     * @return 结果
     */
    @Override
    public int deletePayOrderByIds(String[] ids)
    {
        return payOrderMapper.deletePayOrderByIds(ids);
    }

    /**
     * 删除支付订单信息
     * 
     * @param id 支付订单主键
     * @return 结果
     */
    @Override
    public int deletePayOrderById(String id)
    {
        return payOrderMapper.deletePayOrderById(id);
    }

	@Override
	public WxPayReturnInfo createPayOrder(PayOrderVO payOrder) {
		SysUser user = sysUserService.getById(SecurityUtils.getUserId());
		if(payOrder.getAmount() == null){
			throw new ServiceException("订单金额不能为空");
		}
		String tradeNo = IdUtils.tradeNo();
		WxMaForm wxMaForm = new WxMaForm();
		wxMaForm.setAppId(payOrder.getAppId());
		wxMaForm.setOpenId(user.getOpenId());
		wxMaForm.setTradeNo(tradeNo);
		wxMaForm.setBody(payOrder.getBody());
		wxMaForm.setTotalFee(payOrder.getAmount().multiply(new BigDecimal(100)).intValue());
		wxMaForm.setNotifyUrl("https://wanq.rbtnet.com/pay/payOrder/notifyOrder");
		WxPayReturnInfo wxPayReturnInfo = wxMaPayService.wechatPay(wxMaForm);
		
		PayOrder order = new PayOrder();
		BeanUtils.copyProperties(payOrder, order);
		order.setUserId(String.valueOf(user.getUserId()));
		order.setTradeNo(tradeNo);
		baseMapper.insert(order);
		return wxPayReturnInfo;
	}

	@Override
	public String updatePayOrder(String xmlData) {
		WxPayOrderNotifyInfo notify = wxMaPayService.notifyOrder(xmlData);
		String tradeNo = notify.getTradeNo();
		QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
		PayOrder entity = new PayOrder();
		entity.setTradeNo(tradeNo);
		queryWrapper.setEntity(entity);
		PayOrder payOrder = baseMapper.selectOne(queryWrapper);
		if(payOrder == null){
			return notify.getNotifyResponse();
		}else{
			if("0".equals(payOrder.getStatus())){
				payOrder.setUpdateTime(DateUtils.getNowDate());
				payOrder.setStatus("1");
				baseMapper.updateById(payOrder);
				
				// 充值成功，增加趣币
				SysUser sysUser = sysUserService.getById(payOrder.getUserId());
				PayCoinUser coinUser = new PayCoinUser();
				coinUser.setCoinNum(payOrder.getCoinNum());
				coinUser.setUserId(Long.valueOf(payOrder.getUserId()));
				coinUser.setSourceId(payOrder.getId());
				if(sysUser.getVisitUserId() == null){
					coinUser.setRemark("充值");
				}else{
					coinUser.setRemark("充值:"+sysUser.getVisitUserId());
				}
				coinUser.setIsPay("1");
				payCoinUserMapper.insert(coinUser);
				
				// 更新用户为贵族
				Integer payNum = payCoinUserMapper.querySumPay(Long.valueOf(payOrder.getUserId()));
				sysUser.setIsPay("1");
				sysUser.setPayNum(payNum);
				sysUserService.updateById(sysUser);
			}
		}
		return notify.getNotifyResponse();
	}

	@Override
	public WxPayReturnInfo createVipPayOrder(PayOrderVO payOrder) {
		SysUser user = sysUserService.getById(SecurityUtils.getUserId());
		if(payOrder.getAmount() == null){
			throw new ServiceException("订单金额不能为空");
		}
		String tradeNo = IdUtils.tradeNo();
		WxMaForm wxMaForm = new WxMaForm();
		wxMaForm.setAppId(payOrder.getAppId());
		wxMaForm.setOpenId(user.getOpenId());
		wxMaForm.setTradeNo(tradeNo);
		wxMaForm.setBody(payOrder.getBody());
		wxMaForm.setTotalFee(payOrder.getAmount().multiply(new BigDecimal(100)).intValue());
		wxMaForm.setNotifyUrl("https://wanq.rbtnet.com/pay/payOrder/notifyVipOrder");
		WxPayReturnInfo wxPayReturnInfo = wxMaPayService.wechatPay(wxMaForm);
		
		PayOrder order = new PayOrder();
		BeanUtils.copyProperties(payOrder, order);
		order.setUserId(String.valueOf(user.getUserId()));
		order.setTradeNo(tradeNo);
		baseMapper.insert(order);
		return wxPayReturnInfo;
	}

	@Override
	public String updatePayVipOrder(String xmlData) {
		WxPayOrderNotifyInfo notify = wxMaPayService.notifyOrder(xmlData);
		String tradeNo = notify.getTradeNo();
		QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
		PayOrder entity = new PayOrder();
		entity.setTradeNo(tradeNo);
		queryWrapper.setEntity(entity);
		PayOrder payOrder = baseMapper.selectOne(queryWrapper);
		if(payOrder == null){
			return notify.getNotifyResponse();
		}else{
			if("0".equals(payOrder.getStatus())){
				payOrder.setUpdateTime(DateUtils.getNowDate());
				payOrder.setStatus("1");
				baseMapper.updateById(payOrder);
				
				// 充值成功，增加趣币
				SysUser sysUser = sysUserService.getById(payOrder.getUserId());
				PayCoinUser coinUser = new PayCoinUser();
				coinUser.setCoinNum(payOrder.getCoinNum());
				coinUser.setUserId(Long.valueOf(payOrder.getUserId()));
				coinUser.setSourceId(payOrder.getId());
				coinUser.setIsPay("1");
				if(sysUser.getVisitUserId() == null){
					coinUser.setRemark("充值");
				}else{
					coinUser.setRemark("充值:"+sysUser.getVisitUserId());
				}
				payCoinUserMapper.insert(coinUser);
				
				// 更新用户为贵族
				Integer payNum = payCoinUserMapper.querySumPay(Long.valueOf(payOrder.getUserId()));
				sysUser.setIsPay("1");
				sysUser.setPayNum(payNum);
				sysUserService.updateById(sysUser);
				
				// 充值会员消费趣币
				coinUser = new PayCoinUser();
				coinUser.setCoinNum(payOrder.getCoinNum());
				coinUser.setUserId(Long.valueOf(payOrder.getUserId()));
				coinUser.setSourceId(payOrder.getId());
				coinUser.setRemark("充值会员消费");
				coinUser.setCoinType("1");
				coinUser.setIsPay("1");
				payCoinUserMapper.insert(coinUser);
				
				// 更新用户会员
				Date vipStartTime = new Date();
				Integer offset = 0;
				
				if("abc".contains(sysUser.getAppId())){
					if(payOrder.getCoinNum().equals(1000)){
						offset = 7;
					}else if(payOrder.getCoinNum().equals(2000)){
						offset = 31;
					}else if(payOrder.getCoinNum().equals(4500)){
						offset = 93;
					}
				}else{
					if(payOrder.getCoinNum().equals(2000) || payOrder.getCoinNum().equals(3900) || payOrder.getCoinNum().equals(9900)){
						offset = 7;
					}else if(payOrder.getCoinNum().equals(4000) || payOrder.getCoinNum().equals(7900) || payOrder.getCoinNum().equals(16000) || payOrder.getCoinNum().equals(16800) || payOrder.getCoinNum().equals(8000)){
						offset = 31;
					}else if(payOrder.getCoinNum().equals(9000) || payOrder.getCoinNum().equals(36000) || payOrder.getCoinNum().equals(18000) || payOrder.getCoinNum().equals(29700)){
						offset = 93;
					}else if(payOrder.getCoinNum().equals(106800)){
						offset = 372;
					}else if(payOrder.getCoinNum().equals(12000) || payOrder.getCoinNum().equals(23900) || payOrder.getCoinNum().equals(52000)){
						offset = 186;
					}
				}
				
				
				Date vipEndTime = DateUtil.offsetDay(vipStartTime, offset);
				sysUser.setWechatNum(10);
				sysUser.setPublishNum(3);
				sysUser.setVipStartTime(vipStartTime);
				sysUser.setVipEndTime(vipEndTime);
				sysUserService.updateById(sysUser);
			}
		}
		return notify.getNotifyResponse();
	}

	@Override
	public String updatePayStoreOrder(String xmlData) {
		WxPayOrderNotifyInfo notify = wxMaPayService.notifyOrder(xmlData);
		String tradeNo = notify.getTradeNo();
		QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
		PayOrder entity = new PayOrder();
		entity.setTradeNo(tradeNo);
		queryWrapper.setEntity(entity);
		PayOrder payOrder = baseMapper.selectOne(queryWrapper);
		if(payOrder == null){
			return notify.getNotifyResponse();
		}else{
			if("0".equals(payOrder.getStatus())){
				payOrder.setUpdateTime(DateUtils.getNowDate());
				payOrder.setStatus("1");
				baseMapper.updateById(payOrder);
				
				// 充值成功，增加趣币
				SysUser sysUser = sysUserService.getById(payOrder.getUserId());
				PayCoinUser coinUser = new PayCoinUser();
				coinUser.setCoinNum(payOrder.getCoinNum());
				coinUser.setUserId(Long.valueOf(payOrder.getUserId()));
				coinUser.setSourceId(payOrder.getId());
				coinUser.setIsPay("2");
				if(sysUser.getVisitUserId() == null){
					coinUser.setRemark("充值");
				}else{
					coinUser.setRemark("充值:"+sysUser.getVisitUserId());
				}
				Date dateTime = new Date();
				coinUser.setCreateTime(dateTime);
				payCoinUserMapper.insert(coinUser);
				
				// 更新用户为已支付
				sysUser.setIsPay("1");
				sysUserService.updateById(sysUser);
				
				// 购买商品消费趣币
				coinUser = new PayCoinUser();
				coinUser.setCoinNum(payOrder.getCoinNum());
				coinUser.setUserId(Long.valueOf(payOrder.getUserId()));
				coinUser.setSourceId(payOrder.getId());
				coinUser.setRemark("购买商品消费");
				coinUser.setCoinType("1");
				dateTime = DateUtil.offsetSecond(dateTime, 1);
				coinUser.setCreateTime(dateTime);
				payCoinUserMapper.insert(coinUser);
				
				// 购买商品赠送趣币
				coinUser = new PayCoinUser();
				coinUser.setCoinNum(200);
				coinUser.setUserId(Long.valueOf(payOrder.getUserId()));
				coinUser.setSourceId(payOrder.getId());
				coinUser.setRemark("购买商品赠送");
				coinUser.setCoinType("0");
				dateTime = DateUtil.offsetSecond(dateTime, 1);
				coinUser.setCreateTime(dateTime);
				payCoinUserMapper.insert(coinUser);
			}
		}
		return notify.getNotifyResponse();
	}

	@Override
	public WxPayReturnInfo createStorePayOrder(PayOrderVO payOrder) {
		SysUser user = sysUserService.getById(SecurityUtils.getUserId());
		if(payOrder.getAmount() == null){
			throw new ServiceException("订单金额不能为空");
		}
		String tradeNo = IdUtils.tradeNo();
		WxMaForm wxMaForm = new WxMaForm();
		wxMaForm.setAppId(payOrder.getAppId());
		wxMaForm.setOpenId(user.getOpenId());
		wxMaForm.setTradeNo(tradeNo);
		wxMaForm.setBody(payOrder.getBody());
		wxMaForm.setTotalFee(payOrder.getAmount().multiply(new BigDecimal(100)).intValue());
		wxMaForm.setNotifyUrl("https://wanq.rbtnet.com/pay/payOrder/notifyStoreOrder");
		WxPayReturnInfo wxPayReturnInfo = wxMaPayService.wechatPay(wxMaForm);
		
		PayOrder order = new PayOrder();
		BeanUtils.copyProperties(payOrder, order);
		order.setUserId(String.valueOf(user.getUserId()));
		order.setTradeNo(tradeNo);
		baseMapper.insert(order);
		return wxPayReturnInfo;
	}

	@Override
	public WxPayReturnInfo createPayCardOrder(PayOrderVO payOrder) {
		SysUser user = sysUserService.getById(SecurityUtils.getUserId());
		if(payOrder.getAmount() == null){
			throw new ServiceException("订单金额不能为空");
		}
		String tradeNo = IdUtils.tradeNo();
		WxMaForm wxMaForm = new WxMaForm();
		wxMaForm.setAppId(payOrder.getAppId());
		wxMaForm.setOpenId(user.getOpenId());
		wxMaForm.setTradeNo(tradeNo);
		wxMaForm.setBody(payOrder.getBody());
		wxMaForm.setTotalFee(payOrder.getAmount().multiply(new BigDecimal(100)).intValue());
		wxMaForm.setNotifyUrl("https://wanq.rbtnet.com/pay/payOrder/notifyCardOrder");
		WxPayReturnInfo wxPayReturnInfo = wxMaPayService.wechatPay(wxMaForm);
		
		PayOrder order = new PayOrder();
		BeanUtils.copyProperties(payOrder, order);
		order.setUserId(String.valueOf(user.getUserId()));
		order.setTradeNo(tradeNo);
		baseMapper.insert(order);
		return wxPayReturnInfo;
	}

	@Override
	public WxPayReturnInfo createActivityPayOrder(PayOrderVO payOrder) {
		SysUser user = sysUserService.getById(SecurityUtils.getUserId());
		if(payOrder.getAmount() == null){
			throw new ServiceException("订单金额不能为空");
		}
		String tradeNo = IdUtils.tradeNo();
		WxMaForm wxMaForm = new WxMaForm();
		wxMaForm.setAppId(payOrder.getAppId());
		wxMaForm.setOpenId(user.getOpenId());
		wxMaForm.setTradeNo(tradeNo);
		wxMaForm.setBody(payOrder.getBody());
		wxMaForm.setTotalFee(payOrder.getAmount().multiply(new BigDecimal(100)).intValue());
		wxMaForm.setNotifyUrl("https://wanq.rbtnet.com/pay/payOrder/notifyActivityOrder");
		WxPayReturnInfo wxPayReturnInfo = wxMaPayService.wechatPay(wxMaForm);
		
		PayOrder order = new PayOrder();
		BeanUtils.copyProperties(payOrder, order);
		order.setUserId(String.valueOf(user.getUserId()));
		order.setTradeNo(tradeNo);
		baseMapper.insert(order);
		return wxPayReturnInfo;
	}

	@Override
	public WxPayReturnInfo createTuanPayOrder(PayOrderVO payOrder) {
		SysUser user = sysUserService.getById(SecurityUtils.getUserId());
		if(payOrder.getAmount() == null){
			throw new ServiceException("订单金额不能为空");
		}
		String tradeNo = IdUtils.tradeNo();
		WxMaForm wxMaForm = new WxMaForm();
		wxMaForm.setAppId(payOrder.getAppId());
		wxMaForm.setOpenId(user.getOpenId());
		wxMaForm.setTradeNo(tradeNo);
		wxMaForm.setBody(payOrder.getBody());
		wxMaForm.setTotalFee(payOrder.getAmount().multiply(new BigDecimal(100)).intValue());
		wxMaForm.setNotifyUrl("https://wanq.rbtnet.com/pay/payOrder/notifyTuanOrder");
		WxPayReturnInfo wxPayReturnInfo = wxMaPayService.wechatPay(wxMaForm);
		
		PayOrder order = new PayOrder();
		BeanUtils.copyProperties(payOrder, order);
		order.setUserId(String.valueOf(user.getUserId()));
		order.setTradeNo(tradeNo);
		baseMapper.insert(order);
		return wxPayReturnInfo;
	}
	
}
